package day15.socketdemo07;

import java.io.*;
import java.net.Socket;

/**
 * @author Xiao
 * @date 2021/8/9
 */
public class ClientDemo07 {
    /**
     * 需求：
     * 客户端：将本地文件上传到服务器，接收服务器的反馈；
     * 服务器：接收客户端上传的文件，上传完毕之后给出反馈。
     */
    public static void main(String[] args) throws IOException {
        //创建客户端Socket对象，指定主机和端口
        Socket so = new Socket("127.0.0.1",10000);
        BufferedReader br = getBufferedReader(so);
//        BufferedInputStream bis = getBufferedInputStream(so);
        //标记文件传输完毕
        so.shutdownOutput();
        //创建网络输入流对象
        BufferedReader br1 = new BufferedReader(new InputStreamReader(so.getInputStream()));
        //读入服务器传来的反馈信息
        String s1;
        while ((s1 = br1.readLine()) != null) {
            System.out.println(s1);
        }
        //关闭本地IO流和客户端IO流
        br.close();
//        bis.close();
        so.close();
    }

    /**字节流传输数据*/
    private static BufferedInputStream getBufferedInputStream(Socket so) throws IOException {
        //创建本地缓冲输入流对象
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
                "videoPractice\\src\\day15\\socketdemo07\\demo07.txt"));
        //创建网络输出流对象
        BufferedOutputStream bos = new BufferedOutputStream(so.getOutputStream());
        //通过本地输入流读入本地文件，通过网络输出流写出给服务器
        int i;
        while ((i = bis.read()) != -1) {
            bos.write(i);
        }
        bos.flush();
        return bis;
    }

    /**字符流传输数据*/
    private static BufferedReader getBufferedReader(Socket so) throws IOException {
        //创建本地缓冲输入流对象
        BufferedReader br = new BufferedReader(new FileReader(
               "videoPractice\\src\\day15\\socketdemo07\\demo07.txt"));
        //创建网络输出流对象
        OutputStream os = so.getOutputStream();
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
        //通过本地输入流读入本地文件，通过网络输出流写出给服务器
        String s;
        while ((s = br.readLine()) != null) {
            bw.write(s);
            bw.newLine();
        }
        bw.flush();
        return br;
    }
}
